package com.example.aijiancece.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.aijiancece.R;
import com.example.aijiancece.adapter.HistoryAdapter;
import com.example.aijiancece.database.DatabaseHelper;
import com.example.aijiancece.database.entity.HistoryEntity;
import com.google.android.material.button.MaterialButton;

import java.util.ArrayList;
import java.util.List;

public class HistoryFragment extends Fragment {

    private HistoryAdapter adapter;
    private DatabaseHelper databaseHelper;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_history, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
        MaterialButton btnClear = view.findViewById(R.id.btnClear);

        recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
        adapter = new HistoryAdapter();
        recyclerView.setAdapter(adapter);

        databaseHelper = DatabaseHelper.getInstance(requireContext());

        // 设置点击事件
        adapter.setOnItemClickListener((content, result, analysis) -> {
            // TODO: 显示详细信息
        });

        adapter.setOnDeleteClickListener(id -> {
            databaseHelper.deleteHistory(id);
            loadHistory();
        });

        btnClear.setOnClickListener(v -> {
            databaseHelper.clearHistory();
            loadHistory();
        });

        loadHistory();
    }

    private void loadHistory() {
        new Thread(() -> {
            List<HistoryEntity> histories = databaseHelper.getAllHistory();
            requireActivity().runOnUiThread(() -> {
                adapter.setHistories(histories);
            });
        }).start();
    }
} 